// 获取用户收藏数据云函数
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { limit = 10, skip = 0 } = event
  
  try {
    // 直接使用openid作为用户标识
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录'
      }
    }
    
    const userOpenid = wxContext.OPENID
    
    console.log('获取用户收藏数据，用户OPENID:', userOpenid)

    // 查询用户收藏记录
    const collectionResult = await db.collection('user_collection')
      .where({
        userId: userOpenid
      })
      .get()

    console.log('收藏记录查询结果:', collectionResult)

    if (collectionResult.data.length === 0) {
      // 用户还没有收藏记录，返回空数据
      return {
        success: true,
        data: {
          activities: [],
          goods: []
        },
        message: '暂无收藏数据'
      }
    }

    const userCollection = collectionResult.data[0]
    const { activityLikes = [], goodsLikes = [] } = userCollection

    console.log('用户收藏的活动ID列表:', activityLikes)
    console.log('用户收藏的商品ID列表:', goodsLikes)

    // 并行查询收藏的活动和商品详情
    const [activitiesResult, goodsResult] = await Promise.all([
      // 查询收藏的活动详情
      activityLikes.length > 0 ? 
        db.collection('activities')
          .where({
            _id: db.command.in(activityLikes.slice(skip, skip + limit))
          })
          .orderBy('createdAt', 'desc')
          .get() : 
        { data: [] },
      
      // 查询收藏的商品详情
      goodsLikes.length > 0 ? 
        db.collection('goods')
          .where({
            _id: db.command.in(goodsLikes.slice(skip, skip + limit)),
            status: 1 // 只查询状态为可用的商品
          })
          .orderBy('createdAt', 'desc')
          .get() : 
        { data: [] }
    ])

    console.log('活动详情查询结果:', activitiesResult.data.length, '个')
    console.log('商品详情查询结果:', goodsResult.data.length, '个')

    // 处理活动数据，确保字段兼容
    const processedActivities = activitiesResult.data.map(activity => ({
      ...activity,
      id: activity._id
    }))

    // 处理商品数据，确保字段兼容
    const processedGoods = goodsResult.data.map(goods => ({
      ...goods,
      id: goods._id
    }))

    return {
      success: true,
      data: {
        activities: processedActivities,
        goods: processedGoods
      },
      message: '收藏数据获取成功'
    }

  } catch (error) {
    console.error('获取用户收藏数据失败:', error)
    return {
      success: false,
      message: '获取收藏数据失败',
      error: error.message,
      details: error
    }
  }
}